package com.smh.hmdianping.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.smh.hmdianping.constant.UserConstant;
import com.smh.hmdianping.pojo.User;
import com.smh.hmdianping.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author shiminghui
 * @date 2025/3/27 15:54
 * @description: TODO
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public ResponseResult<String> login(HttpSession session) {
        // 从redis中获取code
        String s = stringRedisTemplate.opsForValue().get(UserConstant.CAPTCHA_PREFIX + "123456");
        if (s == null) {
            return ResponseResult.fail("验证码失效");
        }
        if (!s.equals("123456")) {
            return ResponseResult.fail("验证码错误");
        }
        // 查sql去找用户,如果存在就返回token,不存在则创建,并返回token

        // 将查询的用户信息存到redis中
        User user = new User();
        user.setId(1L);
        user.setName("smh");
        user.setAge(18);
        user.setSex("男");
        Map<String, Object> map = BeanUtil.beanToMap(user, new HashMap<>(),
                CopyOptions.create().ignoreNullValue().setFieldValueEditor((k, v) -> v.toString()));
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("id",user.getId());
//        map.put("name",user.getName());
//        map.put("age",user.getAge());
//        map.put("sex",user.getSex());

        HashOperations hashOperations = redisTemplate.opsForHash();

        // 生成token
        String token = UUID.randomUUID().toString();

        hashOperations.putAll(UserConstant.USER_PREFIX + token, map);
        // 设置过期时间
        redisTemplate.expire(UserConstant.USER_PREFIX + token, 30 * 60, java.util.concurrent.TimeUnit.SECONDS);
        return ResponseResult.success("登录成功");
    }

}
